package com.lemeshko.simple_web_app.dispatcher;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Dispatcher extends HttpServlet {

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		handleRequest(response, request);
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		handleRequest(response, request);
	}

	private void handleRequest(HttpServletResponse response,
			HttpServletRequest request) {

		response.setContentType("contentType=text/html; charset=utf-8");

		HttpSession session = request.getSession();
		String selectedScreen = request.getServletPath();

		if (selectedScreen.equals("/checkRegistration")) {

			String login = request.getParameter("login");
			String password = request.getParameter("password");

			if (login != null) {
				@SuppressWarnings("unchecked")
				HashMap<String, String> usersMap = (HashMap<String, String>) getServletContext()
						.getAttribute("usersMap");

				try {
					if (usersMap.containsKey(login)) {
						request.setAttribute("registrationSuccessful", false);
					} else {

						usersMap.put(login, getHash(password));
						request.setAttribute("registrationSuccessful", true);
					}

					request.getRequestDispatcher("/registrationStatus.jsp")
							.forward(request, response);
				} catch (Exception ex) {
				    // FIXME don't eat exception!!! Always either show them to the user or if there
				    // is no user screens - throw them up.
					ex.printStackTrace();
				}

			}
		} else if (selectedScreen.equals("/chooseLanguage")) {

			String language = request.getParameter("language");
			request.setAttribute("language", language);

			String view = (String) session.getAttribute("view");

			try {
				request.getRequestDispatcher("/" + view + ".jsp").forward(
						request, response);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private String getHash(String str) {

		MessageDigest md5;
		StringBuffer hexString = new StringBuffer();

		try {

			md5 = MessageDigest.getInstance("md5");

			md5.reset();
			md5.update(str.getBytes());

			byte messageDigest[] = md5.digest();

			for (int i = 0; i < messageDigest.length; i++) {
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			}

		} catch (NoSuchAlgorithmException e) {
			return e.toString();
		}

		return hexString.toString();
	}

}
